﻿<script lang="ts" name="syssalesorder" setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import type { FormRules } from "element-plus";
import { formatDate } from '/@/utils/formatTime';
import { generateSalesOrderCode } from '/@/utils/generateCode';
import { useSyssalesorderApi } from '/@/api/order/syssalesorder';
import { useSysOrgApi } from '/@/api/system/sysOrg';
import { useSysUserApi } from '/@/api/system/sysUser';
import { useGoodsModelApi } from '/@/api/Goods/Details/goodsModel';
import { useSyscustomerApi } from '/@/api/interacting/syscustomer';
import { useInventoryQueryApi } from '/@/api/inventory/inventoryQuery';

//父级传递来的函数，用于回调
const emit = defineEmits(["reloadTable"]);
const syssalesorderApi = useSyssalesorderApi();
const sysOrgApi = useSysOrgApi();
const sysUserApi = useSysUserApi();
const goodsModelApi = useGoodsModelApi();
const syscustomerApi = useSyscustomerApi();
const inventoryQueryApi = useInventoryQueryApi();
const ruleFormRef = ref();

const state = reactive({
	title: '',
	loading: false,
	showDialog: false,
	ruleForm: {} as any,
	stores: {},
	dropdownData: {} as any,
	// 下拉框数据
	orgList: [] as any[],
	userList: [] as any[],
	filteredUserList: [] as any[], // 根据部门筛选后的用户列表
	// 货品列表
	goodsList: [] as any[],
	// 客户列表
	customerList: [] as any[],
});

// 自行添加其他规则
const rules = ref<FormRules>({
  code: [{required: true, message: '请选择销售单号！', trigger: 'blur',},],
  documentStatus: [{required: true, message: '请选择单据状态！', trigger: 'change',},],
  salesDate: [{required: true, message: '请选择销售日期！', trigger: 'change',},],
  salesQuantity: [{required: true, message: '请选择销售数量！', trigger: 'blur',},],
  salesAmount: [{required: true, message: '请选择销售金额！', trigger: 'blur',},],
});

// 监听销售货品变化，自动计算销售金额
const onGoodsNameChange = (goodsName: string) => {
	if (goodsName && state.ruleForm.salesQuantity) {
		const selectedGoods = state.goodsList.find(goods => goods.goodsName === goodsName);
		if (selectedGoods && selectedGoods.goodsOutMoney) {
			state.ruleForm.salesAmount = selectedGoods.goodsOutMoney * state.ruleForm.salesQuantity;
		}
	}
};

// 监听销售数量变化，自动计算销售金额
const onSalesQuantityChange = (quantity: number) => {
	if (quantity && state.ruleForm.goodsName) {
		const selectedGoods = state.goodsList.find(goods => goods.goodsName === state.ruleForm.goodsName);
		if (selectedGoods && selectedGoods.goodsOutMoney) {
			state.ruleForm.salesAmount = selectedGoods.goodsOutMoney * quantity;
		}
	}
};

// 监听客户变化，自动填充相关信息
const onCustomerChange = (customerId: number) => {
	if (customerId) {
		const selectedCustomer = state.customerList.find(customer => customer.id === customerId);
		if (selectedCustomer) {
			// 自动填充客户相关信息
			state.ruleForm.customerName = selectedCustomer.customerName;
			state.ruleForm.contactPerson = selectedCustomer.contactPerson;
			state.ruleForm.contactMethod = selectedCustomer.contactPhone;
			state.ruleForm.salesDeptId = selectedCustomer.salesDeptId;
			state.ruleForm.salesManagerId = selectedCustomer.salesManagerId;
			
			// 根据销售部门过滤用户列表，但保持销售负责人选择
			onDeptChange(selectedCustomer.salesDeptId, true);
		}
	} else {
		// 清空相关信息
		state.ruleForm.customerId = null;
		state.ruleForm.customerName = '';
		state.ruleForm.contactPerson = '';
		state.ruleForm.contactMethod = '';
		state.ruleForm.salesDeptId = null;
		state.ruleForm.salesManagerId = null;
	}
};

// 部门变化时筛选用户
const onDeptChange = (deptId: number, keepSalesManager: boolean = false) => {
	if (deptId) {
		// 根据部门ID筛选用户
		state.filteredUserList = state.userList.filter(user => user.orgId === deptId);
	} else {
		// 如果没有选择部门，显示所有用户
		state.filteredUserList = state.userList;
	}
	// 只有在不是从客户反填时才清空已选择的销售负责人
	if (!keepSalesManager) {
		state.ruleForm.salesManagerId = null;
	}
};

// 转换状态为中文显示
const convertStatusToChinese = (status: any) => {
	const statusMap: { [key: string]: string } = {
		// 数字状态码
		'1': '草稿',
		'2': '待审核', 
		'3': '驳回',
		'4': '未出库',  // 销售订单状态4应该是未出库
		'5': '部分出库', // 销售订单状态5应该是部分出库
		'6': '已完成',
		'7': '已关闭',
		// 枚举状态码
		'Draft': '草稿',
		'PendingReview': '待审核',
		'Rejected': '驳回',
		'NotOutOfWarehouse': '未出库',  // 销售订单的NotOutOfWarehouse应该是未出库
		'PartiallyOutOfWarehouse': '部分出库', // 销售订单的部分状态应该是部分出库
		'Completed': '已完成',
		'Closed': '已关闭'
	};
	return statusMap[status] || status;
};

// 转换中文状态为后端格式
const convertStatusToBackend = (status: any) => {
	const statusMap: { [key: string]: number } = {
		'草稿': 1,
		'待审核': 2,
		'驳回': 3,
		'未出库': 4,
		'部分出库': 5,
		'已完成': 6,
		'已关闭': 7
	};
	return statusMap[status] || status;
};

// 页面加载时
onMounted(async () => {
	// 加载机构列表
	try {
		const orgRes = await sysOrgApi.getList();
		state.orgList = orgRes.data.result || [];
	} catch (error) {
		console.error('加载机构列表失败:', error);
	}
	
	// 加载用户列表
	try {
		const userRes = await sysUserApi.getList();
		state.userList = userRes.data.result || [];
		state.filteredUserList = userRes.data.result || []; // 初始显示所有用户
	} catch (error) {
		console.error('加载用户列表失败:', error);
	}
	
	// 加载货品列表
	try {
		const goodsRes = await goodsModelApi.page({ page: 1, pageSize: 9999 });
		state.goodsList = goodsRes.data.result?.items || [];
	} catch (error) {
		console.error('加载货品列表失败:', error);
	}
	
	// 加载客户列表
	try {
		const customerRes = await syscustomerApi.page({ page: 1, pageSize: 9999 });
		state.customerList = customerRes.data.result?.items || [];
	} catch (error) {
		console.error('加载客户列表失败:', error);
	}
});

// 打开弹窗
const openDialog = async (row: any, title: string) => {
	state.title = title;
	row = row ?? {};
	
	if (row.id) {
		// 编辑模式：获取完整数据
		state.ruleForm = await syssalesorderApi.detail(row.id).then(res => res.data.result);
		
		// 转换单据状态为中文显示
		state.ruleForm.documentStatus = convertStatusToChinese(state.ruleForm.documentStatus);
		
		// 根据客户名称设置客户ID
		if (state.ruleForm.customerName && state.customerList.length > 0) {
			const matchedCustomer = state.customerList.find(customer => customer.customerName === state.ruleForm.customerName);
			if (matchedCustomer) {
				state.ruleForm.customerId = matchedCustomer.id;
			}
		}
	} else {
		// 新增模式：初始化表单数据，确保必填字段有默认值
		state.ruleForm = {
			code: generateSalesOrderCode(), // 销售单号 - 自动生成
			documentStatus: 1, // 默认状态
			salesDate: new Date(), // 销售日期
			customerId: null, // 客户ID
			customerName: '', // 客户名称
			contactPerson: '', // 联系人
			contactMethod: '', // 联系方式
			salesDeptId: null, // 销售部门ID
			salesManagerId: null, // 销售负责人ID
			salesQuantity: 1, // 销售数量，默认为1
			salesAmount: 0, // 销售金额，默认为0
			goodsName: '', // 货品名称
			remark: '', // 备注
			createUserId: 1300000000001, // 任杰的用户ID
			createUserName: "任杰", // 任杰的用户名
		};
	}
	
	state.showDialog = true;
};

// 关闭弹窗
const closeDialog = () => {
	emit("reloadTable");
	state.showDialog = false;
};

// 提交
const submit = async () => {
	ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
		if (isValid) {
			// 额外验证必填字段
			if (!state.ruleForm.code || state.ruleForm.code.trim() === '') {
				ElMessage.error('销售单号不能为空！');
				return;
			}
			if (!state.ruleForm.salesQuantity || state.ruleForm.salesQuantity <= 0) {
				ElMessage.error('销售数量必须大于0！');
				return;
			}
			if (state.ruleForm.salesAmount === null || state.ruleForm.salesAmount === undefined || state.ruleForm.salesAmount < 0) {
				ElMessage.error('销售金额不能为空且不能小于0！');
				return;
			}
			
			// 校验库存：销售数量不能大于商品可用库存
			if (state.ruleForm.goodsName && state.ruleForm.salesQuantity) {
				try {
					const inventoryResult = await inventoryQueryApi.page({
						page: 1,
						pageSize: 10,
						goodsName: state.ruleForm.goodsName
					});
					
					const inventoryItems = inventoryResult.data.result?.items || [];
					if (inventoryItems.length > 0) {
						const currentStock = inventoryItems[0].currentStock || 0;
						const availableStock = inventoryItems[0].availableStock || 0;
						
						// 判断销售数量是否超过可用库存
						if (state.ruleForm.salesQuantity > availableStock) {
							ElMessage.error(`销售数量（${state.ruleForm.salesQuantity}）不能大于商品可用库存（${availableStock}）！当前库存：${currentStock}，可用库存：${availableStock}`);
							return;
						}
					} else {
						ElMessage.error(`未找到商品"${state.ruleForm.goodsName}"的库存信息！`);
						return;
					}
				} catch (error: any) {
					console.error('查询库存失败:', error);
					ElMessage.warning('无法查询库存信息，请手动确认库存是否充足！');
				}
			}
			
			try {
				let values = { ...state.ruleForm };
				// 转换中文状态为后端需要的格式
				values.documentStatus = convertStatusToBackend(values.documentStatus);
				await syssalesorderApi[state.ruleForm.id ? 'update' : 'add'](values);
				ElMessage.success(state.ruleForm.id ? '更新成功！' : '新增成功！');
				closeDialog();
			} catch (error: any) {
				console.error('提交失败:', error);
				ElMessage.error('提交失败：' + (error.message || '未知错误'));
			}
		} else {
			ElMessage({
				message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
				type: "error",
			});
		}
	});
};

//将属性或者函数暴露给父组件
defineExpose({ openDialog });
</script>
<template>
	<div class="syssalesorder-container">
		<el-dialog v-model="state.showDialog" :width="800" draggable :close-on-click-modal="false">
			<template #header>
				<div style="color: #fff">
					<span>{{ state.title }}</span>
				</div>
			</template>
			<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="auto" :rules="rules">
				<el-row :gutter="35">
					<el-form-item v-show="false">
						<el-input v-model="state.ruleForm.id" />
					</el-form-item>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="销售单号" prop="code">
							<el-input 
								v-model="state.ruleForm.code" 
								placeholder="销售单号" 
								maxlength="64" 
								show-word-limit 
								:readonly="true"
								style="background-color: #f5f7fa;"
							/>
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="单据状态" prop="documentStatus">
							<el-select v-model="state.ruleForm.documentStatus" placeholder="请选择单据状态" clearable filterable style="width: 100%">
								<el-option label="草稿" value="1" />
								<el-option label="待审核" value="2" />
								<el-option label="驳回" value="3" />
								<el-option label="未出库" value="4" />							
								<el-option label="已完成" value="6" />
								<el-option label="已关闭" value="7" />
							</el-select>
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="销售日期" prop="salesDate">
							<el-date-picker v-model="state.ruleForm.salesDate" type="date" placeholder="销售日期" />
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="客户名称" prop="customerId">
							<el-select 
								v-model="state.ruleForm.customerId" 
								placeholder="请选择客户" 
								clearable 
								filterable
								style="width: 100%"
								@change="onCustomerChange"
							>
								<el-option
									v-for="customer in state.customerList"
									:key="customer.id"
									:label="customer.customerName"
									:value="customer.id"
								/>
							</el-select>
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="联系人" prop="contactPerson">
							<el-input v-model="state.ruleForm.contactPerson" placeholder="请输入联系人" maxlength="64" show-word-limit clearable />
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="联系方式" prop="contactMethod">
							<el-input v-model="state.ruleForm.contactMethod" placeholder="请输入联系方式" maxlength="32" show-word-limit clearable />
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="销售部门" prop="salesDeptId">
							<el-select v-model="state.ruleForm.salesDeptId" placeholder="请选择销售部门" clearable filterable @change="(deptId) => onDeptChange(deptId, false)">
								<el-option
									v-for="org in state.orgList"
									:key="org.id"
									:label="org.name"
									:value="org.id"
								/>
							</el-select>
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="销售负责人" prop="salesManagerId">
							<el-select v-model="state.ruleForm.salesManagerId" placeholder="请选择销售负责人" clearable filterable>
								<el-option
									v-for="user in state.filteredUserList"
									:key="user.id"
									:label="user.realName"
									:value="user.id"
								/>
							</el-select>
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="销售货品" prop="goodsName">
							<el-select 
								v-model="state.ruleForm.goodsName" 
								placeholder="请选择销售货品" 
								clearable 
								filterable
								style="width: 100%"
								@change="onGoodsNameChange"
							>
								<el-option
									v-for="goods in state.goodsList"
									:key="goods.id"
									:label="goods.goodsName"
									:value="goods.goodsName"
								/>
							</el-select>
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="销售数量" prop="salesQuantity">
							<el-input-number 
								v-model="state.ruleForm.salesQuantity" 
								placeholder="请输入销售数量" 
								clearable 
								@change="onSalesQuantityChange"
							/>
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="销售金额" prop="salesAmount">
							<el-input-number v-model="state.ruleForm.salesAmount" placeholder="请输入销售金额" clearable />
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="备注" prop="remark">
							<el-input v-model="state.ruleForm.remark" placeholder="请输入备注" maxlength="512" show-word-limit clearable />
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="软删除时间" prop="deleteTime">
							<el-date-picker v-model="state.ruleForm.deleteTime" type="date" placeholder="软删除时间" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="() => state.showDialog = false">取 消</el-button>
					<el-button @click="submit" type="primary" v-reclick="1000">确 定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<style lang="scss" scoped>
:deep(.el-select), :deep(.el-input-number) {
  width: 100%;
}
</style>